/**
 * DataSource Form Component
 *
 * 数据源表单组件 (FR-002, FR-003, FR-005)
 * - 创建/编辑数据源
 * - 表单验证
 * - 连接测试
 */

import React, { useEffect, useState } from 'react'
import { Form, Input, InputNumber, Select, Switch, Button, Space, Alert } from 'antd'
import { DatabaseOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons'
import type { FormInstance } from 'antd'
import { useTestDataSourceConnection } from '@/hooks/useDataSource'
import {
  DatabaseType,
  DB_TYPE_NAMES,
  DB_TYPE_DEFAULT_PORTS,
  type DataSource,
  type DataSourceCreateRequest,
  type DataSourceUpdateRequest,
} from '@/services/models/types'

interface DataSourceFormProps {
  /** 表单实例 (由父组件通过Form.useForm()创建) */
  form: FormInstance<DataSourceCreateRequest | DataSourceUpdateRequest>
  /** 初始数据 (编辑模式) */
  initialValues?: DataSource
  /** 是否为编辑模式 */
  isEditMode?: boolean
  /** 提交回调 */
  onSubmit: (values: DataSourceCreateRequest | DataSourceUpdateRequest) => void
  /** 取消回调 */
  onCancel: () => void
  /** 是否正在提交 */
  submitting?: boolean
}

const DataSourceForm: React.FC<DataSourceFormProps> = ({
  form,
  initialValues,
  isEditMode = false,
  onSubmit,
  onCancel,
  submitting = false,
}) => {
  const [testConnectionResult, setTestConnectionResult] = useState<{
    success: boolean
    message: string
  } | null>(null)
  const testConnectionMutation = useTestDataSourceConnection()

  // 数据库类型选项
  const dbTypeOptions = Object.entries(DB_TYPE_NAMES).map(([value, label]) => ({
    value,
    label,
  }))

  /**
   * 处理数据库类型变更 - 自动填充默认端口
   */
  const handleDbTypeChange = (dbType: DatabaseType) => {
    const defaultPort = DB_TYPE_DEFAULT_PORTS[dbType]
    if (defaultPort && !form.getFieldValue('port')) {
      form.setFieldsValue({ port: defaultPort })
    }
    // 清除测试结果
    setTestConnectionResult(null)
  }

  /**
   * 测试连接
   */
  const handleTestConnection = async () => {
    try {
      // 验证必填字段
      await form.validateFields(['dbType', 'host', 'port', 'databaseName', 'username', 'password'])

      const values = form.getFieldsValue([
        'dbType',
        'host',
        'port',
        'databaseName',
        'username',
        'password',
      ])

      const result = await testConnectionMutation.mutateAsync(values)
      setTestConnectionResult({
        success: result.success,
        message: result.message || (result.success ? '连接成功' : '连接失败'),
      })
    } catch (error) {
      // 表单验证失败 - 不显示测试结果
      setTestConnectionResult(null)
    }
  }

  /**
   * 表单提交
   */
  const handleFinish = (values: DataSourceCreateRequest | DataSourceUpdateRequest) => {
    // 清除密码字段的空白字符
    if (values.password) {
      values.password = values.password.trim()
    }
    onSubmit(values)
  }

  /**
   * 初始化表单数据 (编辑模式)
   */
  useEffect(() => {
    if (isEditMode && initialValues) {
      form.setFieldsValue({
        name: initialValues.name,
        description: initialValues.description,
        dbType: initialValues.dbType,
        host: initialValues.host,
        port: initialValues.port,
        databaseName: initialValues.databaseName,
        username: initialValues.username,
        enabled: initialValues.enabled,
        // 密码不回显 (安全考虑)
        password: undefined,
      })
    }
  }, [isEditMode, initialValues, form])

  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={handleFinish}
      initialValues={{
        enabled: true, // 默认启用
        port: 3306, // 默认MySQL端口
      }}
      autoComplete="off"
    >
      {/* 基本信息 */}
      <Form.Item
        name="name"
        label="数据源名称"
        rules={[
          { required: true, message: '请输入数据源名称' },
          { max: 100, message: '名称不能超过100个字符' },
          {
            pattern: /^[\u4e00-\u9fa5a-zA-Z0-9_-]+$/,
            message: '名称只能包含中文、英文、数字、下划线和连字符',
          },
        ]}
        tooltip="用于识别数据源的唯一名称"
      >
        <Input placeholder="例如: 生产环境MySQL" prefix={<DatabaseOutlined />} />
      </Form.Item>

      <Form.Item name="description" label="描述" rules={[{ max: 500, message: '描述不能超过500个字符' }]}>
        <Input.TextArea
          placeholder="可选的数据源描述信息"
          rows={3}
          showCount
          maxLength={500}
        />
      </Form.Item>

      {/* 数据库连接信息 */}
      <Form.Item
        name="dbType"
        label="数据库类型"
        rules={[{ required: true, message: '请选择数据库类型' }]}
      >
        <Select
          placeholder="选择数据库类型"
          options={dbTypeOptions}
          onChange={handleDbTypeChange}
        />
      </Form.Item>

      <Space.Compact style={{ width: '100%' }}>
        <Form.Item
          name="host"
          label="主机地址"
          rules={[{ required: true, message: '请输入主机地址' }]}
          style={{ flex: 1, marginBottom: 0 }}
        >
          <Input placeholder="例如: localhost 或 192.168.1.100" />
        </Form.Item>

        <Form.Item
          name="port"
          label="端口"
          rules={[
            { required: true, message: '请输入端口号' },
            { type: 'number', min: 1, max: 65535, message: '端口号范围: 1-65535' },
          ]}
          style={{ width: 120, marginBottom: 0 }}
        >
          <InputNumber placeholder="3306" style={{ width: '100%' }} />
        </Form.Item>
      </Space.Compact>

      <Form.Item
        name="databaseName"
        label="数据库名"
        rules={[
          { required: true, message: '请输入数据库名' },
          { max: 100, message: '数据库名不能超过100个字符' },
        ]}
        tooltip="要采集元数据的目标数据库名称"
      >
        <Input placeholder="例如: production_db" />
      </Form.Item>

      <Form.Item
        name="username"
        label="用户名"
        rules={[
          { required: true, message: '请输入用户名' },
          { max: 100, message: '用户名不能超过100个字符' },
        ]}
      >
        <Input placeholder="数据库用户名" autoComplete="off" />
      </Form.Item>

      <Form.Item
        name="password"
        label={isEditMode ? '密码 (留空表示不修改)' : '密码'}
        rules={[
          { required: !isEditMode, message: '请输入密码' },
          { max: 200, message: '密码不能超过200个字符' },
        ]}
        tooltip={isEditMode ? '出于安全考虑,密码不会回显。如需修改请重新输入' : undefined}
      >
        <Input.Password placeholder="数据库密码" autoComplete="new-password" />
      </Form.Item>

      {/* 连接测试结果 */}
      {testConnectionResult && (
        <Alert
          message={testConnectionResult.success ? '连接测试成功' : '连接测试失败'}
          description={testConnectionResult.message}
          type={testConnectionResult.success ? 'success' : 'error'}
          icon={
            testConnectionResult.success ? <CheckCircleOutlined /> : <CloseCircleOutlined />
          }
          showIcon
          closable
          onClose={() => setTestConnectionResult(null)}
          style={{ marginBottom: 16 }}
        />
      )}

      {/* 测试连接按钮 */}
      <Form.Item>
        <Button
          type="dashed"
          onClick={handleTestConnection}
          loading={testConnectionMutation.isPending}
          block
        >
          {testConnectionMutation.isPending ? '测试中...' : '测试连接'}
        </Button>
      </Form.Item>

      {/* 启用状态 */}
      <Form.Item
        name="enabled"
        label="启用状态"
        valuePropName="checked"
        tooltip="禁用后,该数据源不会出现在采集任务的数据源选择列表中"
      >
        <Switch checkedChildren="启用" unCheckedChildren="禁用" />
      </Form.Item>

      {/* 操作按钮 */}
      <Form.Item>
        <Space>
          <Button type="primary" htmlType="submit" loading={submitting}>
            {isEditMode ? '保存' : '创建'}
          </Button>
          <Button onClick={onCancel}>取消</Button>
        </Space>
      </Form.Item>
    </Form>
  )
}

export default DataSourceForm
